// 这里打造   /shop  这个接口 

const express = require( 'express' )

const router = express.Router()

const { shop } = require('../db')

const multer = require('multer')

const path = require('path')


const arr = []
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // cb(null, 磁盘存储路径)
    cb(null, path.resolve(__dirname,'../public/upload'))
  },
  filename: function (req, file, cb) {
    const fileStr = file.originalname // 1.jpg
    const fileIndex = fileStr.indexOf('.')
    const fileEnd = fileStr.substr( fileIndex )
    const filename = file.fieldname + '-' + Date.now() + fileEnd
    arr.push(filename)
    req.fileNameArr = arr
    cb(null, filename )
  }
})
 


var upload = multer({ storage: storage })

var cpUpload = upload.fields([
  { name: 'shop_logo', maxCount: 1 }, 
  { name: 'business_license', maxCount: 1 },
  { name: 'catering_license',maxCount: 1}
])


// /shop/add
// router.get('/shop',( req,res,next ) => {})
// router.post()
// router.put()
// router.delete

/* 
  下面使用了 resetful api 的规则来打造接口，通过暴露四种不同类型的接口，对应四种数据操作
    增 ： post
    删 : delete
    改 : put
    查 : get
*/
router.route('/shop')
  .get( async ( req,res,next ) => {

    const result = await shop.query()

    res.render('shop',{
      data: JSON.stringify( result )
    })
  })
  .post(cpUpload, async ( req,res,next ) => { //增
    req.body.filename = req.fileNameArr

    // 修改提交时间
    req.body.shop_hours = req.body.shop_start_time + '/' + req.body.shop_end_time

    //数据库操作
    const status = await shop.add( {...req.body} )
    // 返回给前台的内容
    res.render('shop',{
      data: JSON.stringify({
        ret: true,
        status
      })
    })

    arr.length = 0
  })
  .put()
  .delete( async ( req,res,next ) => {
    const { id } = req.body 
    const status = await shop.delete( id )
    const result = await shop.query()
    // 做数据库操作
    res.render('shop',{
      data: JSON.stringify({
        ret: true,
        status,
        result
      })
    })
  })



router.get('/shop/edit', async ( req,res,next ) => {
  const { id } = req.query 
  const result = await shop.queryById( id )
  res.render('shop',{
    data: JSON.stringify({
      ret: true,
      result
    })
  })
})




module.exports = router